import React, {useState, useEffect} from 'react';
import {connect} from 'react-redux';
import {
  TextInput,
  View,
  ScrollView,
  StyleSheet,
  Text,
  SafeAreaView,
  Image,
  Dimensions,
  Alert,
  PermissionsAndroid,
} from 'react-native';
import {NetworkInfo} from 'react-native-network-info';
import Overlay from '@/components/Overlay';
import {setUserInfo, setAuth} from '@/store/action/user';
import {login, queryUserMultiLoginConfig} from '@/apis/api';
import {Button, CheckBox} from '@rneui/themed';
import StorageUtils from '@/utils/storageUtils';
import * as rootNavigation from '@/utils/rootNavigation';
import {useTranslation} from 'react-i18next';
const {width} = Dimensions.get('window');
const formDefaultData = {
  userName: '',
  password: '',
  remember: false,
};

function Form(props: any) {
  const {t} = useTranslation();
  const {setUserInfo, setAuth} = props;
  const [formData, setFormData] = useState(formDefaultData);
  const [isLoading, setIsLoading] = useState(false);
  const [isMultiLogin, setIsMultiLogin] = useState(false);
  const [ipAddr, setIpAddr] = useState('');
  const requestMultiplePermission = async () => {
    try {
      const permissions = [
        PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        PermissionsAndroid.PERMISSIONS.CAMERA,
        PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS,
      ];
      //返回得是对象类型
      const granteds = await PermissionsAndroid.requestMultiple(permissions);
      var data = '是否同意地址权限: ';
      if (granteds['android.permission.ACCESS_FINE_LOCATION'] === 'granted') {
        data = data + '是\n';
      } else {
        data = data + '否\n';
      }
      data = data + '是否同意相机权限: ';
      if (granteds['android.permission.CAMERA'] === 'granted') {
        data = data + '是\n';
      } else {
        data = data + '否\n';
      }
      data = data + '是否同意存储权限: ';
      if (granteds['android.permission.WRITE_EXTERNAL_STORAGE'] === 'granted') {
        data = data + '是\n';
      } else {
        data = data + '否\n';
      }
      data = data + '是否同意通知权限: ';
      if (granteds['android.permission.POST_NOTIFICATIONS'] === 'granted') {
        data += '是\n';
      } else {
        data += '否\n';
      }
    } catch (err) {}
  };
  useEffect(() => {
    requestMultiplePermission();
    showUserName();
  }, []);

  const showUserName = async () => {
    const userName = await StorageUtils.getItem('userName');
    const password = await StorageUtils.getItem('password');
    setFormData({
      ...formData,
      userName,
      password,
      remember: !!userName,
    });
  };

  const handleLogin = async () => {
    setIsLoading(true);
    const res = await queryUserMultiLoginConfig({username: formData.userName});
    let ipAddress = '';
    let hasMultiLogin = false;
    if (res?.data === 1) {
      setIsMultiLogin(true);
      hasMultiLogin = true;
      ipAddress = await NetworkInfo.getIPAddress();
      setIpAddr(ipAddress);
    }
    const params = {username: formData.userName, password: formData.password};
    if (ipAddress && hasMultiLogin) {
      params.device_ip = ipAddress;
    }
    try {
      let res = await login(params);
      const {user_id, username} = res;
      setAuth(res);
      if (formData.remember) {
        StorageUtils.setItem('userName', username);
        StorageUtils.setItem('password', formData.password);
      } else {
        StorageUtils.removeItem('userName');
        StorageUtils.removeItem('password');
      }
      const userInfo = {
        user_id,
        username,
      };
      setUserInfo(userInfo);

      /**
       * 清空路由
       */
      rootNavigation.reset('Layout');
    } catch (err) {
    } finally {
      setIsLoading(false);
    }
  };

  const handleForgetPwd = () => {
    try {
      rootNavigation.navigate('PwdForget');
    } catch (err: any) {
      console.log(err);
      Alert.alert(t('sys_tip'), err.msg || err.message);
    }
  };

  const handleRemember = async () => {
    setFormData({
      ...formData,
      remember: !formData.remember,
    });
    await StorageUtils.setItem(
      'rememberMe',
      formData.remember ? 'true' : 'false',
    );
  };
  return (
    <SafeAreaView style={styles.flex}>
      <Overlay isShow={isLoading} />
      <ScrollView contentContainerStyle={styles.contentContainer}>
        <View>
          <Image
            style={styles.image}
            source={require('@/assets/images/login.png')}
          />
          <Text style={styles.logoText}>{t('sys_login')}</Text>
          <Text style={styles.logoText}>{t('sys_welcomeBack')}</Text>
        </View>
        <TextInput
          placeholder={t('sys_usernameInputTip')}
          onChangeText={text =>
            setFormData({
              ...formData,
              userName: text,
            })
          }
          value={formData.userName}
          style={[styles.inputStyle, styles.borderStyle]}
        />
        <TextInput
          secureTextEntry={true}
          placeholder={t('sys_plsInputPwd')}
          onChangeText={text =>
            setFormData({
              ...formData,
              password: text,
            })
          }
          value={formData.password}
          style={[styles.inputStyle, styles.borderStyle]}
        />

        <View style={[styles.otherAction]}>
          <CheckBox
            containerStyle={{
              marginLeft: 0,
              paddingLeft: 0,
              backgroundColor: 'transparent',
            }}
            title={t('sys_rememberMe')}
            iconType="material-community"
            checked={formData.remember}
            checkedIcon="checkbox-outline"
            uncheckedIcon={'checkbox-blank-outline'}
            onPress={() => handleRemember()}
          />
          <Button
            title={t('sys_forgetPassword')}
            size="md"
            type="clear"
            onPress={handleForgetPwd}
          />
        </View>

        <View style={[styles.inputStyle]}>
          <Button
            radius={'md'}
            disabled={!formData.userName || !formData.password}
            style={[styles.button]}
            onPress={handleLogin}>
            {t('sys_login')}
          </Button>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
}

export default connect(
  (state: any) => ({
    userInfo: state.user.userInfo,
    auth: state.user.auth,
  }),
  dispatch => ({
    setUserInfo: (data: any) => dispatch(setUserInfo(data)),
    setAuth: (token: any) => dispatch(setAuth(token)),
  }),
)(Form);
const styles = StyleSheet.create({
  flex: {
    display: 'flex',
    flex: 1,
    backgroundColor: '#fff',
  },
  contentContainer: {
    display: 'flex',
    flex: 1,
    justifyContent: 'center',
    marginTop: 10,
    paddingBottom: 15,
  },
  image: {
    width: 160,
    height: 160,
    resizeMode: 'stretch',
    marginLeft: 'auto',
    marginRight: 'auto',
    marginBottom: 10,
  },
  logoText: {
    width: width * 0.85,
    marginLeft: 'auto',
    marginRight: 'auto',
    fontSize: 20,
    color: '#000',
    marginBottom: 10,
  },
  borderStyle: {
    borderColor: '#cacaca',
    borderWidth: 1,
  },
  otherAction: {
    width: width * 0.85,
    marginLeft: 'auto',
    marginRight: 'auto',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  inputStyle: {
    width: width * 0.85,
    marginLeft: 'auto',
    marginRight: 'auto',
    height: 40,
    marginTop: 15,
    borderRadius: 5,
    marginBottom: 15,
  },
  button: {
    marginTop: 15,
  },
});
